/**
 * Match a String against the given pattern, supporting the following simple
 * pattern styles: "xxx*", "*xxx", "*xxx*" and "xxx*yyy" matches (with an
 * arbitrary number of pattern parts), as well as direct equality.
 * @param pattern the pattern to match against
 * @param str the String to match
 * @return boolean the String matches the given pattern
 */
export function simpleMatch(pattern, str) {
  if (pattern == null || str == null) {
    return false
  }

  const firstIndex = pattern.indexOf('*')
  if (firstIndex == -1) {
    return pattern === str
  }

  if (firstIndex == 0) {
    if (pattern.length == 1) {
      return true
    }
    const nextIndex = pattern.indexOf('*', 1)
    if (nextIndex == -1) {
      return str.endsWith(pattern.substring(1))
    }
    const part = pattern.substring(1, nextIndex)
    if (!part) {
      return simpleMatch(pattern.substring(nextIndex), str)
    }
    let partIndex = str.indexOf(part)
    while (partIndex != -1) {
      if (simpleMatch(pattern.substring(nextIndex), str.substring(partIndex + part.length))) {
        return true
      }
      partIndex = str.indexOf(part, partIndex + 1)
    }
    return false
  }

  return (str.length >= firstIndex &&
    pattern.substring(0, firstIndex) === (str.substring(0, firstIndex)) &&
    simpleMatch(pattern.substring(firstIndex), str.substring(firstIndex)))
}
